import { onMounted, onBeforeUnmount, ref, getCurrentInstance, reactive } from 'vue'
import { createLoading, MyResponse } from '@/type'
import { UnwrapNestedRefs } from '@vue/reactivity'
/**
 *
 * 定时器对性能影响应该不会很大，并且能灵活控制时间
 * @param callback
 */
export const onPageShown2 = (callback: () => void) => {
  const timeout = ref<any>(-1)

  onMounted(() => {
    timeout.value = setTimeout(() => {
      callback()
    }, 500)
  })

  onBeforeUnmount(() => {
    clearTimeout(timeout.value)
  })
}

/* 第二种方案，也可行，不过也要改造App.vue */

export const onPageShown = (callback: () => void) => {
  const currentInstance = getCurrentInstance()

  if (!currentInstance) {
    return
  }

  if (currentInstance.exposed) {
    currentInstance.exposed.onPageShown = function () {
      callback()
    }
  } else {
    currentInstance.exposed = {
      onPageShown: () => {
        callback()
      }
    }
  }
}

export function onRightBtnClicked(callback: () => void) {
  const currentInstance = getCurrentInstance()
  if (!currentInstance) {
    return
  }
  if (currentInstance.exposed) {
    currentInstance.exposed.rightBthClick = function () {
      callback()
    }
  } else {
    currentInstance.exposed = {
      rightBthClick: () => {
        callback()
      }
    }
  }
}

type TypeBeforeUpdate<T> = (data: T) => any

type TypePageResp<T> = [
  UnwrapNestedRefs<MyResponse<T>>,
  (promise: Promise<MyResponse<T>>, beforeUpdate?: TypeBeforeUpdate<T>) => Promise<MyResponse<T>>
]

export function usePageResp<T = any>(data: T): TypePageResp<T> {
  const resp = reactive<MyResponse<T>>(createLoading<T>(data))

  function send(promise: Promise<MyResponse<T>>, beforeUpdate?: TypeBeforeUpdate<T>) {
    resp.setLoading(data)
    return promise.then((res) => {
      if (res.success) {
        beforeUpdate && beforeUpdate(res.data)
      }
      resp.update(res)
      return res
    })
  }
  return [resp, send]
}
